package com.di.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.di.base.dao.StorageTblDao;
import com.di.base.entity.StorageTbl;
import com.di.base.service.StorageTccService;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
public class StorageTccServiceImpl implements StorageTccService {

    @Resource
    private StorageTblDao storageMapper;

    @Override
    @Transactional
    public boolean prepareDecrease(BusinessActionContext context,
                                   String productId,
                                   Integer count) {
        log.info("[TCC Try] 预扣库存，productId={}，count={}", productId, count);
        // 逻辑：库存减少count，冻结库存增加count
        StorageTbl storage = storageMapper.selectOne(new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId),false);
        if (storage.getCount() < count) {
            log.error("库存不足");
            return false;
        }

        storage.setCount(storage.getCount() - count);
        storage.setFrozen(storage.getFrozen() + count);

        storageMapper.update(storage,new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId));
        return true;
    }

    @Override
    @Transactional
    public boolean commitDecrease(BusinessActionContext context) {
        String productId = context.getActionContext("productId").toString();
        Integer count = Integer.parseInt(context.getActionContext("count").toString());
        log.info("[TCC Confirm] 确认扣减冻结库存，productId={}，count={}", productId, count);

        StorageTbl storage = storageMapper.selectOne(new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId),false);
        storage.setFrozen(storage.getFrozen() - count);
        storageMapper.update(storage,new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId));
        return true;
    }

    @Override
    @Transactional
    public boolean rollbackDecrease(BusinessActionContext context) {
        String productId = context.getActionContext("productId").toString();
        Integer count = Integer.parseInt(context.getActionContext("count").toString());
        log.info("[TCC Cancel] 回滚库存预扣，productId={}，count={}", productId, count);

        StorageTbl storage = storageMapper.selectOne(new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId),false);
        storage.setCount(storage.getCount() + count);
        storage.setFrozen(storage.getFrozen() - count);
        storageMapper.update(storage,new QueryWrapper<StorageTbl>().lambda().eq(StorageTbl::getProductId,productId));
        return true;
    }
}
